package com.tianxia120.website.admin.service;

import cn.hutool.core.util.IdUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.upload.UploadFile;
import com.tianxia120.website.bean.model.Banner;
import com.tianxia120.website.data.utils.CommonUtils;
import com.tianxia120.website.data.utils.FieldUtils;
import com.tianxia120.website.data.utils.FileImageUtils;

import java.util.List;

/**
 * @createTime: 2018/9/21 13:49
 * @author: HingLo
 * @description: BannerService
 */
public class BannerService {
    /**
     * 上传banner图
     *
     * @param banner banner对象
     * @param img    图片对象
     * @return 返回结果
     */
    public boolean addService(Banner banner, UploadFile img) {
        if (img != null && FileImageUtils.iconUtils(img.getOriginalFileName())) {
            //文件上传限制
            if (img.getFile().length() > FieldUtils.HEADER_SIZE) {
                throw new RuntimeException("图片大小不能超过2M");
            }
            //生成图片名称
            String imgName = IdUtil.simpleUUID()+ ".png";
            //保存发票的扫面件
            boolean bool = FileImageUtils.saveImageUtils(img, imgName, FieldUtils.IMAGE_1);
            //设置图片名称
            if (bool) {
                banner.setImage(imgName);
            } else {
                return false;
            }
            return banner.save();
        } else {
            return false;
        }
    }

    public List<Banner> listService() {
        String sql = Db.getSql("website.banner-list");
        List<Banner> list = Banner.dao.find(sql);
        // 组装图片链接
        list.forEach(x -> x.setImage(CommonUtils.imgInstall(x.getImage(), FieldUtils.IMAGE_1)));
        return list;
    }
}
